package com.lujianfei.netease_android_canvas.ui

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.os.Bundle
import android.view.View
import android.view.animation.PathInterpolator
import androidx.appcompat.app.AppCompatActivity
import com.lujianfei.netease_android_canvas.R
import com.lujianfei.netease_android_canvas.utils.DensityUtils

class BezierAnimActivity : AppCompatActivity() {

    var view: View? = null
    var objectAnimator: ValueAnimator? = null
    // 控制点 (0,0.9)，用于实现贝塞尔曲线的加速效果，两个的值范围[0,1]
    private val p1_x = 0f
    private val p1_y = 0.9f
    // 起点和终点
    private var startValue = 0f
    private var endValue = 0f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bezier_anim)
        view = findViewById(R.id.view)
        // 动画变速器，采用贝塞尔曲线控制
        val interpolator = PathInterpolator(p1_x, p1_y)
        // 起点
        startValue = 0f
        // 终点
        endValue = DensityUtils.getScreenWidth(this) - DensityUtils.dip2px(this, 50f).toFloat()
        view?.let { viewNonNull ->
            objectAnimator = ObjectAnimator.ofFloat(viewNonNull,
                    "translationX",
                    startValue,
                    endValue)
            objectAnimator?.apply {
                setInterpolator(interpolator) // 给到变速器
                duration = 2000
                repeatCount = ValueAnimator.INFINITE
                start()
            }
        }
    }

    override fun onDestroy() {
        objectAnimator?.cancel()
        super.onDestroy()
    }
}
